/**
 * Copyright 2015 | build time: 2015-4-20
 */
define(function(require, exports, module) {
	var storage = window.localStorage;
	var _location = window.location;
	var $ = jQuery;
	var $body = top.jQuery("body");
	var _$body = jQuery("body");
	var laypagejs = require("laypagejs");
    var laypageCss = require("laypageCss");

	var T = {
		// 版本号
		"version" : "1.0",
		// 数据请求锁
		"fnAjaxLock" : false,
		// 存储时间
		"expireTime" : (function() {
			return storage.getItem("expireTime");
		})(),
		// 当前页面使用的sid
		"sid" : (function() {
			return storage.getItem("sid");
		})(),
		// 文件服务器地址
		"fsServer" : "http://120.36.136.250:18888"
	};
	// 方法:地址参数获取
	T.getUrlParam = function(name) {
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
		var r = _location.search.substr(1).match(reg);
		if (r != null)
			return unescape(r[2]);
		return null;
	};

	// 方法:本地数据保存方式
	T.saveData = function(n, d) {
		storage.setItem(n, d);
	};
	// 获取
	T.getData = function(n) {
		return storage.getItem(n);
	};
	// 清除数据保存
	T.clearData = function(item) {
		if (!item) {
			storage.clear();
		} else {
			storage.clear(item);
		}
	};
	// 打开新窗口
	T.openUrl = function(url, settings) {
		if (settings == "new") {
			window.open(url);
			return;
		}
		_location.href = url;

	};
	// 提示信息 1,success 2.alert 3.error
	T.alert = function(type, c, timeout) {
		// $("#mes-alert-"+type).remove();
//		var $mesCommon = $("<div>").addClass("mesCommon").attr("id", "mes-alert-" + type);
//		var $mesCon = $("<p>").addClass("mesCon").html(c);
//		$mesCommon.append($mesCon);
//		_$body.append($mesCommon);
//		var ml = $mesCommon.width() / 2;
//		$mesCommon.css("margin-left", "-" + ml + "px");
//		var ti = timeout ? timeout : 1500;
//		setTimeout(function() {
//			$(".mesCommon").remove();
//		}, ti);
		if (type == 1) {
			if (c == null) {
				c = "获取信息失败";
			}
			var ti = timeout ? timeout : 1500;
			layer.msg(
				c, 
				{
					time: ti, icon:type
				}
			);
		} else {
			if (c == null) {
				c = "获取信息失败";
			}
			var ti = timeout ? timeout : 1500;
			layer.msg(
				c, 
				{
					time: 0, icon:type, shadeClose: true, shade: 0.3, closeBtn: 1
				}
			);
		}
	}
	// 方法:服务端数据请求
	T.fnAjax = function(oArg) {
		var ii = layer.load(1, {
		  shade: [0.5,'#ccc'] //0.5透明度的灰色背景
		});
		if (T.fnAjaxLock) {
			return;
		}
		// T.saveData("sid","cfaab2de0f334538b84cfff8b6f3addc");//方便调试
		// 当前用户是否切换检测
		if (T.sid && T.getData("sid") && (T.sid != T.getData("sid"))) {
			T.alert(2, "账号信息过期，该页面即将进行重置。", 2000);
			setTimeout(function() {
				 top.window.location = "../login/login.html";
			}, 2000);
			return;
		}

		// 是否需要登录
		if (!oArg.nocode) {
			var d = T.getData("sid");
			if (!d) {
				 top.window.location = "../login/login.html"; // TODO
				return;
			}
			oArg.oData = oArg.oData || {};
		}

		// 请求路径
		var Path = {
			"fs" : CONFIG.fsPath,
			"zp" : CONFIG.ApiPath
		}[oArg.Path || "zp"];

		var re = /[\u4e00-\u9fa5]+/, oData = [], n, v; // 处理oArg.oData中的数组

		// 请求参数oData
		if (oArg.oData) {
			if (typeof oArg.oData == 'string') {
				oData = oArg.oData;
			} else {
				for (n in oArg.oData) {
					if (oArg.oData[n] instanceof Array) {
						for ( var k in oArg.oData[n]) {
							oData.push({
								name : n,
								value : oArg.oData[n][k]
							});
						}
					} else {
						v = oArg.oData[n];
						v = $.isFunction(v) ? v() : v; // if value is fn, invoke it
						oData.push({
							name : n,
							value : v
						});
					}
				}
			}
		}
		oData.push({
			name : "sessionUuid",
			value : T.getData("sid")
		}); // sessionUuid
		oData.push({
			name : "appKey",
			value : T.getData("appKey")
		}); // appKey
		oData.push({
			name : "randomUuid",
			value : GenNonDuplicateID()
		});

		// 版本号
		var ApiVersion = oArg.version || CONFIG.ApiVersion;
		// 参数组合
		var opts = {
			url : Path + ApiVersion + "/" + oArg.action + "",
			type : oArg.stype || "POST",
			async : oArg.async == false ? false : true, // 默认异步
			dataType : oArg.dataType || 'json',
			data : oData,
			success : function(oRes) {
				if (oRes && oRes.flag == "UNLOGIN") {
					 top.window.location = "../login/login.html";
					return;
				}
				oArg.fnSuccess && oArg.fnSuccess(oRes);
				layer.closeAll('loading');
			},
			error : function(jqXHR, textStatus, errorThrown) {
				T.alert(3, "服务器异常,请稍后再试", 2000);
				oArg.error && oArg.error();
				layer.closeAll('loading');
			}
		};

		$.ajax(opts);
	};
	
	var GenNonDuplicateID = function(){
	 var idStr = Date.now().toString(36);
	 idStr += Math.random().toString(36).substr(3);
	 return idStr;
	}

	// 方法:表格分页
	T.myPage = function(page_dom, t, n, p, callback) {
		var page_text = page_dom.find("#page_text");
		var page_tol = page_dom.find("#page_tol");
		var page_prev = page_dom.find("#page_prev");
		var page_next = page_dom.find("#page_next");
		if (t) {
			var tpage = Math.ceil(t / p);
			var now_page = n;
			page_text.html('共<span>' + t + '</span>条记录 当前每页显示<span>' + p + '</span>条').show();
			page_tol.html('<input type="text" id="junmpage" class="input" value="' + n + '">/' + tpage + '页  <a href="javascript:void(0);">确定</a>');
			page_tol.show();
			if (n == 1) {
				page_prev.hide();
			} else {
				page_prev.show();
			}
			if (n < tpage) {
				page_next.show();
			} else {
				page_next.hide();
			}
			var junmpage = page_tol.find("#junmpage");
			var cpage = function(p) {
				junmpage.val(p);
				now_page = p;
				if (now_page == 1) {
					page_prev.hide();
				} else {
					page_prev.show();
				}
				if (now_page < tpage) {
					page_next.show();
				} else {
					page_next.hide();
				}
				callback(p);
			}
			junmpage.unbind().keypress(function(e) {
				e.keyCode == 13 && page_tol.find("a").click();
			});
			page_tol.find("a").unbind().bind('click', function() {
				var _v = junmpage.val();
				if (!_v.match(new RegExp("^[0-9]*[1-9][0-9]*$"))) {
					junmpage.val(now_page);
					return;
				} // 非正整数
				if (_v > tpage) {
					junmpage.val(now_page);
					return;
				} // 不大于总页数
				if (_v == now_page) {
					return;
				} // 当前页不请求
				cpage(parseInt(_v));
			});
			page_prev.unbind().bind('click', function() {
				cpage(--now_page);
			});
			page_next.unbind().bind('click', function() {
				cpage(++now_page);
			});
		} else {
			page_tol.hide();
			page_prev.hide();
			page_next.hide();
			page_text.hide();
		}
	}
	// 方法：数字分页(page_dom是占位的分页节点，t是数据总条数，n是当前页，p是分页的大小，callback是分页的回调函数)
	T.pageControl = function(page_dom, t, n, p, callback) {
		var _p = $(page_dom);
		_p.unbind();
		var page_num = $("<ul>").addClass("pagenation");
		var page_text = $("<div>").addClass("page_text");
		var page_tol = $("<div>").addClass("page_tol");
		_p.html("").append(page_num).append(page_text).append(page_tol);

		var now_page = n;
		var tpage = Math.ceil(t / p);

		if (tpage > 1) { // 总页码大于1
			page_text.html("共" + t + "条，" + tpage + "页，到第");
			var junmpageId = _p.attr("id") + "junmpage";
			page_tol.html('<input type="number" id="' + junmpageId + '" class="input junmpage" value="' + n + '">/' + tpage + '页  <a class="button">确定</a>');

			var draw = function(tpage, n) {
				var now_page = n; // 当前页
				var pgCt = tpage; // 总页数

				var html = [];
				html.push('<li class="pagenation-first">首页</li>');
				html.push('<li class="pagenation-pre">&lt;上一页</li>');
				$.each(T.genPage(now_page, pgCt), function(idx, itm) {
					if (itm == now_page) {
						html.push('<li class="pagenation-num active" data-page="' + itm + '">' + itm + '</li>');
					} else {
						html.push('<li class="pagenation-num" data-page="' + itm + '">' + itm + '</li>');
					}
				});
				html.push('<li class="pagenation-next" title="下一页">下一页&gt;</li>');
				html.push('<li class="pagenation-last">末页</li>');

				page_num.html(html.join(""));
			}
			draw(tpage, n); // 生成数字

			var junmpageIdStr = "#" + junmpageId;
			var junmpage = page_tol.find(junmpageIdStr);
			var cpage = function(p) {
				junmpage.val(p);
				now_page = p;
				callback(p);
				draw(tpage, p);
			}
			junmpage.unbind().keypress(function(e) {
				e.keyCode == 13 && page_tol.find("a").click();
			});
			page_tol.find("a").unbind().bind('click', function() {
				var _v = junmpage.val();
				if (!_v.match(new RegExp("^[0-9]*[1-9][0-9]*$"))) {
					junmpage.val(now_page);
					return;
				} // 非正整数
				if (_v > tpage) {
					junmpage.val(now_page);
					return;
				} // 不大于总页数
				if (_v == now_page) {
					return;
				} // 当前页不请求
				cpage(parseInt(_v));
			});

			_p.on("click", ".pagenation-num", function(e) {
				e.preventDefault();
				if (now_page == $(this).attr("data-page")) {
					return;
				}
				now_page = $(this).attr("data-page"); // 获取页码
				cpage(parseInt($(this).attr("data-page")));
			});

			_p.on("click", ".pagenation-first", function(e) {
				e.preventDefault();
				cpage(1)
			});
			_p.on("click", ".pagenation-pre", function(e) {
				e.preventDefault();
				if (now_page > 1) {
					cpage(now_page - 1);
				}
			});

			_p.on("click", ".pagenation-next", function(e) {
				e.preventDefault();
				if (tpage > now_page) {
					cpage(now_page + 1);
				}

			});

			_p.on("click", ".pagenation-last", function(e) {
				e.preventDefault();
				if (n != tpage) {
					cpage(tpage);
				}
			});
		}
	};
	// 辅助数字分页
	T.genPage = function(currentpage, TotalPage) {
		var ret = [];
		currentpage = parseInt(currentpage);
		TotalPage = parseInt(TotalPage);

		var min, max;
		if (TotalPage > 10) {
			if (currentpage < 6) {
				min = 1;
				max = 10;
			} else {
				if (TotalPage - currentpage < 4) {
					max = TotalPage;
					min = TotalPage - 9 < 1 ? 1 : TotalPage - 9;
				} else {
					min = (currentpage - 5) > 1 ? currentpage - 5 : 1;
					max = (currentpage + 4) > TotalPage ? TotalPage : currentpage + 4
				}
			}
		} else {
			min = 1;
			max = TotalPage;
		}
		for (var i = min; i <= max; i++) {
			ret.push(i);
		}

		return ret;
	}
	// 生成参数对象
	T.parseForm = function(dom) {
		if (!dom) {
			dom = document;
		}
		var _d = $(dom);
		var ins = _d.find("input,textarea,select");
		var form = {};
		$.each(ins, function(idx, item) {
			var _t = $(item);
			if (_t.attr("type") == "checkbox" || _t.attr("type") == "radio") {
				if (!_t.is(":checked")) {
					return;
				}
			}
			var name = _t.attr("name");
			if (!name) {
				return;
			}
			var val = _t.val();
			var exists = form[name];
			if (!exists) {

			} else {
				if (exists.push) {
					exists.push(val);
					val = exists;
				} else {
					var nv = [];
					nv.push(exists);
					nv.push(val)
					val = nv;
				}

			}
			form[name] = val;
		});
		return form;
	}

	// 方法:统计字数
	// ==================
	T.checkNum = function(textarea, textnum, maxnum, callback) {
		textarea.on("paste cut keydown keyup focus", function(e) {
			if (e.keyCode && $.inArray(e.keyCode, [ 37, 38, 39, 40 ]) > -1)
				return; // 不处理方向键
			var _t = this;
			var _length = _t.value.length;
			// 更新可输入文字数
			_length > maxnum && (function() {
				_t.value = _t.value.substring(0, maxnum);
			})();

			_length = _t.value.length;
			textnum.html(maxnum - _length);
			callback && callback(_length);
		});
	};

	// 方法:返回格式化日期 TODO:需要加上时分吗
	// ==================
	T.nowDate = function(hm) {
		var now = hm ? new Date(hm) : new Date();
		var ydd = [ now.getFullYear(), now.getMonth() + 1, now.getDate() ];
		return [ ydd[0], ydd[1] > 9 ? ydd[1] : '0' + ydd[1], ydd[2] > 9 ? ydd[2] : '0' + ydd[2] ];
	};

	// 表格获取数据方法
	T.listView = function(tabledom, lineHandler, after_callback) {
		var t = T;
		var data = t.parseForm(tabledom);
		var _td = $(tabledom);

		var actionName = _td.attr("data-action-name");
		var actionVersion = _td.attr("data-action-version");

		t.fnAjax({
			action : actionName,
			async : false,
			version : actionVersion,
			oData : data,
			fnSuccess : function(data) {
				var dta = data.datas;
				if (data.status == 200) {
					var lines = [];
					$.each(dta, function(idx, item) {
						lines.push(lineHandler(item));
					});
					_td.find(".table-header").after(lines.join(""));
					/*
					 * var pg = t.findInput(_td, "pageIndex"); if (pg) { $(pg).val(data.pageIndex); } var pc = t.findInput(_td,
					 * "totalPageCount"); if (pc) { $(pc).val(data.totalPageCount); } var totoDom = t.findInput(_td, "totalRecordCount");
					 * if(totoDom.length==0){ totoDom = $('<input type="hidden" name="totalRecordCount"
					 * value="'+data.totalRecordCount+'"/>'); _td.append(totoDom); } if (totoDom) { $(totoDom).val(data.totalRecordCount); }
					 * _td.trigger("onChange"); if (after_callback) { after_callback(tabledom,data); }
					 */
				} else {
					T.alert(3, "服务器异常,请稍后再试", 2000);
					oArg.error && oArg.error();
				}
			},
			error : function(data) {
				T.alert(3, data.message);
			}
		});
	};

	T.apply = function(a, b) {
		for ( var property in b) {
			a[property] = b[property];
		}
	};

	T.applyIf = function(a, b) {
		for ( var property in b) {
			if (a[property] == undefined) {
				a[property] = b[property];
			}
		}
	};

	T.findInput = function(dom, name) {
		var ins = $(dom).find("input,select,textarea");
		var ret = [];
		$.each(ins, function(idx, item) {
			if ($(item).attr("name") == name) {
				ret.push(item);
			}
		});
		return ret;
	};

	module.exports = T;
});